<template>
    <div class="page-bg an-cart">
      <div class="an-head">
        <div class="an-title">购物车</div>
        <div class="an-btn" @click="()=>{sysShow = sysShow?false:true}">{{ sysShow?'完成':'管理'}}</div>
      </div>

      <van-list
        v-if="list.length>0"
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div v-for="(goods,index) in list" :key="goods.id" class="an-goods">
          <van-checkbox class="an-check" v-model="list[index].checked" checked-color="#ee0a24"></van-checkbox>
          <van-card
            class="an-van-card"
            :price="goods.goodsPrice"
            :thumb="goods.goods.image"
            :title="goods.goods.name"
            @click-thumb="toUrl(goods.goodsID)"
          >
            <template #tags v-if="!isEmpty(goods.standardID)">
              <div class="an-subtitle">{{goods.standardName}}</div>
            </template>
            <template #num>
              <van-stepper
                v-model.number="list[index].goodsNum"
                theme="round"
                button-size="22"
                @plus="numChange(goods, index)"
                @minus="numChange(goods, index)"/>
            </template>
          </van-card>
        </div>
      </van-list>
      <van-empty v-else description="暂无数据" />

      <van-submit-bar
        :price="totalPrice"
        button-text="结算"
        tip="合计金额不包含运费，运费单独计算"
        @submit="onSubmit">
        <van-checkbox v-model="allChecked" checked-color="#ee0a24" @click="checkAll">全选</van-checkbox>
        <template #button v-if="sysShow">
          <van-button plain size="small" type="danger" round @click="deleteCart"> 删 除 </van-button>
        </template>
      </van-submit-bar>

    </div>
</template>

<script>
import { mapState } from "vuex";
import {isEmpty} from "@/utils/auth";
export default {
  data() {
    return{
      sysShow: false, // 是否为管理模式
      num:1,
      allChecked:true, // 全选
      list:[],
      loading: false,
      finished: false,
      getData:{
        page:1,
        pageSize:10,
        userID:'',
        isCollect: 0 // 查购物车
      },
      total:0
    };
  },
  computed: {
    ...mapState(['userInfo','isLogin','cart']),
    totalPrice() { // 总金额
      let nd = 0;
      this.list.forEach(item => {
        if(item.checked) {
          nd = nd + item.goodsNum * item.goodsPrice * 100;
        }
      });
      return nd;
    }
  },
  watch:{
    list:{
      deep:true, // 深度监听设置为 true
      handler:function(newV) {
        this.listChange(newV);
      }
    }
  },
  created() {
    this.anLoad();
  },
  methods:{
    isEmpty,
    anLoad() {
      if(this.isLogin) {
        this.getList(1);
      }else{
      // 非登录状态
        this.finished = true;
        this.list = this.cart;
      }
      this.sysShow = false;
    },

    // 查询列表
    getList(page) {
      if(page) {
        this.getData.page = page;
      }
      if(page==1) {
        this.list = [];
      }
      this.getData.userID = this.userInfo.id;
      this.$api.getCart(this.getData).then(res => {
        this.loading = false;
        let nd = [...res.records];
        nd.forEach(item => {
          this.list.push(this.$auth.addCartChange(item.goods, item.standardID, item.goodsNum, item.id)) ;
        });
        this.total = res.total;
        // 判断是否存在下一页数据
        if(this.total <= this.getData.page * this.getData.pageSize) {
          this.finished = true;
        }
        this.checkAll();
        // 更新购物车商品数量
        this.$store.commit('SET_CARTNUMBER', this.total);
      });
    },

    // 上拉加载
    onLoad() {
      let page = this.getData.page;
      page++;
      if(this.total > this.getData.page * this.getData.pageSize) {
        this.getList(page);
      }
    },

    // 全选
    checkAll() {
      if(this.allChecked) {
        // 全选
        this.list.forEach(item => {
          item.checked = true;
        });
      }else{
        // 全不选
        this.list.forEach(item => {
          item.checked = false;
        });
      }
    },

    // 结算
    onSubmit() {
      if(this.isLogin) {
        let nd = [];
        this.list.forEach(item => {
          if(item.checked) {
            nd.push(item);
          }
        });
        if(nd.length==0) {
          return this.$toast('请先选择需要结算的商品');
        }
        let prom = encodeURI(JSON.stringify(nd));
        this.$router.push({path:"/order", query:{prom:prom}});
      }else{
        this.$toast('请先登录');
      }
    },

    // 删除
    deleteCart() {
      let nd = [];
      let checkIds = [];
      this.list.forEach(item => {
        if(item.checked) {
          checkIds.push(item.id);
        }else{
          nd.push(item);
        }
      });
      this.list = nd;
      let ids = checkIds.toString();
      if(this.isLogin) {
        // 登录状态
        this.$api.deleteCart(ids).then(() => {
          // 更新购物车商品数量
          this.$store.dispatch('getCartNumber');
        });
      }else{
        this.$store.dispatch('addCart', this.list);
      }
    },

    // 购物车改变了
    listChange(array) {
      let allChecked = true;
      // 有一个没有选中 就取消全选状态
      array.forEach(item => {
        if(!item.checked) {
          allChecked = false;
        }
      });
      this.allChecked = allChecked;
    },

    // 商品数量改变
    numChange(goods, index) {
      setTimeout(() => {
        if(this.isLogin) {
          // 登录状态
          let cart = [{
            id: goods.id,
            goodsNum: this.list[index].goodsNum
          }];
          let nd = {
            userID: this.$store.state.userInfo.id,
            attrValues: encodeURI(JSON.stringify(cart))
          };
          this.$api.postCart(nd);
        }else{
          // 非登录状态
          this.$store.dispatch('addCart', this.list);
        }
      },3000);
    },

    // 详情
    toUrl(id) {
      this.$router.push({ path: '/goods', query: { id: id }});
    }
  }
};
</script>

<style lang="scss">
.an-cart{
  .van-card{
    background-color: #ffffff;
  }
  .van-submit-bar{
    bottom: 50px;
  }
  .van-list{
    padding-bottom: 135px;
  }
}

</style>
<style lang="scss" scoped>
@import '../../css/mixin.scss';
.an-cart{
  .an-head{
    padding: 10px;
    position: relative;
    .an-title{
      font-size: 20px;
    }
    .an-btn{
      position: absolute;
      right: 10px;
      bottom: 10px;
    }
  }
  .an-goods{
    margin: 0 10px 10px 10px;
    border-radius: 10px;
    overflow: hidden;
    background-color: #ffffff;
    display: flex;
    .an-check{
      flex:0 0 auto;
      margin-left: 10px;
    }
    .an-van-card{
      flex:1 1 auto;
      .an-subtitle{
        color: $gray-6;
        padding: 5px 0;
      }
    }
  }
}
</style>